package com.yqb.study.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.yqb.study.constant.key.ICookieKey;

/**
 * cookie工具类 Created by 廖师兄 2017-07-30 16:31
 */
public class CookieUtil {

	/**
	 * 在response中写入cookie
	 * 
	 * @param response
	 * @param name 键名字   
	 * @param value 值
	 * @param maxAge 过期时间
	 */
	public static void set(HttpServletResponse response, String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		cookie.setMaxAge(maxAge);
		response.addCookie(cookie);
	}

	/**
	 * 从request中获取cookie
	 * 
	 * @param request
	 * @param name 键名字   
	 * @return
	 */
	public static Cookie get(HttpServletRequest request, String name) {
		Map<String, Cookie> cookieMap = readCookieMap(request);
		if (cookieMap.containsKey(name)) {
			return cookieMap.get(name);
		} else {
			return null;
		}
	}
	
	/**
	 * 从request中获取cookie中的value值
	 * 
	 * @param request
	 * @param name 键名字   
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, String name) {
		Cookie cookie = get(request, name);
		if (cookie != null) {
			return cookie.getValue();
		} else {
			return null;
		} 
	}	
	
	public static String getToken(HttpServletRequest request, String name) {
		// 有的token从cookie中带入，有的是从request请求中带入
		String paramToken = request.getParameter(ICookieKey.TOKEN_KEY);
		String cookieToken = CookieUtil.getCookieValue(request, ICookieKey.TOKEN_KEY);
		if (StringUtils.isAllEmpty(paramToken, cookieToken)) {
			return null;		
		}
		// 取到浏览器发送来的token，从第三方缓存中取到对应的session
		return StringUtils.isEmpty(paramToken) ? cookieToken : paramToken; 
	}	

	/**
	 * 将cookie封装成Map
	 * 
	 * @param request
	 * @return
	 */
	private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<>();
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}
}
